<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">{{ total }}条记录</span>
        <template #after>
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExecl">导出</el-button>
          <el-button size="small" type="primary" @click="dialogShow">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 表格标签 -->
      <el-card v-loading="loading">
        <el-table :border="true" style="width: 100%" :data="allUser">
          <el-table-column
            type="index"
            prop="date"
            label="序号"
            width="180"
          />
          <el-table-column
            prop="username"
            label="姓名"
            width="180"
          />
          <el-table-column label="头像" width="120">
            <template slot-scope="{row}">
              <img
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                @click="codeFn(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="workNumber"
            label="工号"
            width="180"
          />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            width="180"
            :formatter="formatterEmployment"
          />
          <el-table-column
            prop="departmentName"
            label="部门"
            width="180"
          />
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
            width="180"
          >
            <template slot-scope="obj">
              {{ obj.row.timeOfEntry |formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            prop="enableState"
            label="账户状态"
            width="180"
          >
            <template slot-scope="obj">
              <el-switch :value="obj.row.enableState===1" />
            </template>
          </el-table-column>
          <el-table-column
            prop="date"
            label="操作"
            width="280"
            fixed="right"
          >
            <template slot-scope="obj">
              <el-button type="text" size="small" @click="$router.push({name:'detail',params:{detailId:obj.row.id}})">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="roleBtn(obj.row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delUserApi(obj.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页标签 -->
        <el-row type="flex" justify="center" style="height:60px" align="middle">
          <el-pagination
            :total="total"
            :current-page="update.page"
            :page-size="update.size"
            layout="prev, pager, next"
            @current-change="pageChange"
          />
        </el-row>
      </el-card>
      <!-- 弹出层 -->
      <el-dialog :visible="isShow" title="新增员工" @close="closeFn">
        <el-form ref="form" :model="FormData" label-position="left" label-width="120px" :rules="rules">
          <el-form-item label="姓名" prop="username">
            <el-input v-model="FormData.username" placeholder="请输入姓名" style="width:80%" />
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="FormData.mobile" placeholder="请输入手机号" style="width:60%" />
          </el-form-item>
          <el-form-item label="入职时间">
            <el-col>
              <el-date-picker v-model="FormData.timeOfEntry" type="date" placeholder="选择日期" style="width: 50%;" />
            </el-col>
          </el-form-item>
          <el-form-item label="聘用形式">
            <el-select v-model="FormData.formOfEmployment" placeholder="请选择" style="width:60%">
              <el-option v-for="itm in employees.hireType" :key="itm.id" :label="itm.value" :value="itm.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="工号" prop="workNumber">
            <el-input v-model="FormData.workNumber" placeholder="请输入工号" style="width:60%" />
          </el-form-item>
          <el-form-item label="部门" prop="departmentName">
            <el-input v-model="FormData.departmentName" placeholder="请输入部门" style="width:60%" @focus="treeShowFn" />
            <el-tree v-show="treeShow" class="treeDiv" :data="treeData" :props="defaultProps" :default-expand-all="true" @node-click="handleNodeClick" />
          </el-form-item>
          <el-form-item label="转正时间">
            <el-date-picker v-model="FormData.correctionTime" type="date" placeholder="选择日期" style="width: 50%;" />
          </el-form-item>
        </el-form>
        <el-row type="flex" justify="center" align="middle" style="height:80px">
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button type="default" @click="closeFn">取消</el-button>
        </el-row>
      </el-dialog>
      <!-- 二维码弹出层 -->
      <el-dialog title="生成二维码" :visible.sync="codeShow">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <assignRole :id="userId" ref="roleRef" :role-show.sync="roleShow" />
    </div>
  </div>
</template>

<script>
import employees from '@/api/constant/employees'
import { getAllUserApi, delUserApi, addEmployees } from '@/api/employees'
import { getDepartments } from '@/api/departments'
import { transformTreeData } from '@/utils/index'
import { formatDate } from '@/filters'
import Qrcode from 'qrcode'
import assignRole from './components/assign-role.vue'
export default {
  name: 'Employees',
  components: {
    assignRole
  },
  props: {
    showBefore: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      userId: '',
      // 分配角色弹层
      roleShow: false,
      // 二维码显示隐藏
      codeShow: false,
      employees,
      isShow: false,
      treeShow: false,
      loading: false,
      allUser: [],
      total: null,
      update: {
        page: 1,
        size: 10
      },
      // 树形结构数据
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 树形结构数据
      // 表单绑定数据
      FormData: {
        username: '',
        mobile: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        timeOfEntry: '',
        correctionTime: ''
      },
      rules: {
        username: [{ required: true, message: '用户姓名不能为空', trigger: 'blur' }, {
          min: 1, max: 4, message: '用户姓名为1-4位'
        }],
        mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }, {
          pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'
        }],
        formOfEmployment: [{ required: true, message: '聘用形式不能为空', trigger: 'blur' }],
        workNumber: [{ required: true, message: '工号不能为空', trigger: 'blur' }],
        departmentName: [{ required: true, message: '部门不能为空', trigger: 'change' }],
        timeOfEntry: [{ required: true, message: '入职时间', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getAllUserApi()
  },
  methods: {
    pageChange(page) {
      this.update.page = page
      this.getAllUserApi()
    },
    // 获取员工列表
    async getAllUserApi() {
      this.loading = true
      const { total, rows } = await getAllUserApi(this.update)
      this.total = total
      this.allUser = rows
      this.loading = false
    },
    // 删除员工
    async delUserApi(id) {
      try {
        await this.$confirm('确定删除嘛', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning' })
        await delUserApi(id)
        this.getAllUserApi()
        this.$message.success('删除成功')
      } catch (err) {
        console.log(err)
      }
    },
    // 弹出层显示
    async dialogShow() {
      const { depts } = await getDepartments()
      const newDepts = depts.filter(itm => !(itm.name === '总裁办'))
      this.treeData = transformTreeData(newDepts, '')
      this.isShow = true
    },
    // 关闭弹出层
    closeFn() {
      this.isShow = false
      this.$refs.form.resetFields()
      this.FormData = {
        username: '',
        mobile: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        timeOfEntry: '',
        correctionTime: ''
      }
    },
    treeShowFn() {
      this.treeShow = true
    },
    // 提交按钮
    async submit() {
      try {
        await this.$refs.form.validate()
        await addEmployees(this.FormData)
        this.$message.success('添加成功')
        this.getAllUserApi()
        this.isShow = false
      } catch (err) {
        console.log(err)
      }
    },
    formatterEmployment(row, column, cellValue, index) {
      const type = employees.hireType.filter(itm => itm.id === cellValue)
      return cellValue ? type[0].value : ''
    },
    handleNodeClick(data) {
      this.FormData.departmentName = data.name
      this.treeShow = false
    },
    // 导出Execl
    async   exportExecl() {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      const { rows } = await getAllUserApi({ page: 1,
        size: this.total })
      const data = this.getArrandArr(rows, headers)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          // 具体数据 必填
          data
          // filename: 'excel-list', // 非必填
          // autoWidth: true, // 非必填
          // bookType: 'xlsx' // 非必填
        })
      })
    },
    // 转换数组嵌套数组
    getArrandArr(list, headers) {
      var arr = []
      list.forEach((itm, index) => {
        var outArr = []
        Object.values(headers).forEach(obj => {
          var prop = itm[obj] ? itm[obj] : ''
          if (itm[obj] && (obj === 'timeOfEntry' || obj === 'correctionTime')) {
            outArr.push(formatDate(prop))
          } else if (obj === 'formOfEmployment') {
            const em = employees.hireType.filter(item => item.id === prop)
            outArr.push(em[0] && em[0].value ? em[0].value : '未知')
          } else {
            outArr.push(prop)
          }
        })
        arr.push(outArr)
      })
      return arr
    },
    // 二维码
    async codeFn(url) {
      try {
        if (url) {
          this.codeShow = true
          await this.$nextTick()
          Qrcode.toCanvas(this.$refs.myCanvas, url)
        } else {
          this.$message.warning('该用户还未上传头像')
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 分配角色按钮
    async roleBtn(id) {
      this.userId = id
      await this.$refs.roleRef.getRoleById(id)
      this.roleShow = true
    }
  }
}

</script>

<style lang="scss" scoped>
.treeDiv{
  position: absolute;
  z-index: 999;
  width:250px;
  border: 1px solid #dddee1;
  border-radius: 5px;;
}
</style>>

